import {
  forwardRef,
  useImperativeHandle,
  useEffect,
  useState,
  Ref,
} from 'react';
import { Input, AutoComplete } from 'antd';
import { Field } from '@formily/core';
import { connect, useField, mapProps } from '@formily/react';
import { useEvents } from '@inbiz/utils';
import { getMessage } from '@inbiz/react';
import { useModelList } from '@inbiz/hooks';
import { defaultProps } from '../../designer/schema';
import api from './api';
import './style.less';


type IProps = {
  controlId: string;
  value: string;
  // onChange: Function
  readOnly: boolean;
  disabled: boolean;
  addonAfter: string;
  title: string;
  inbiz: { appInfo: { appId: string } };
  sourceModel: string;
  onChange: (value: string) => void;
  callBackEvents?: {
    onBeforeChange?: (v: string) => boolean;
  };
  viewMode?: string;
  emit?: {
    /** 自动完成框搜索内容变化时触发 */
    (type: 'onSerch', value?: any): void;
    /** 自动完成框选中条目时触发 */
    (type: 'onSelect', value?: string, options?: object): void;
  };
} & typeof defaultProps;

type IRef = Ref<ReturnType<typeof api>>;
const iconNoEnterReg =
  /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/gi;

const EformInput = forwardRef((props: IProps, ref: IRef) => {
  const [options, setOptions] = useState<{ value: string }[]>([]);
  const {
    callBackEvents,
    emit,
    defaultValueType,
    systemDefaultValue,
    autoComplete,
    autoCompleteFiled,
    inbiz,
    sourceModel,
    type,
    allowClear,
    placeholder,
    title,
    controlId,
    viewMode,
    ...others
  } = props;
  const [configEvents] = useEvents(props.callBackEvents, props.emit);
  const { runAsync, loading } = useModelList(configEvents);
  const filed = useField<Field>();
  useEffect(() => {
    if (
      autoCompleteFiled &&
      autoCompleteFiled?.length > 0 &&
      autoComplete == true &&
      (props.value || props.value?.length > 0)
    ) {
      runAsync({
        appId: props.inbiz.appInfo.appId,
        key: props.sourceModel,
        pageInfo: {
          index: 1,
          size: 10,
        },
        queryGroups: [
          {
            index: 0,
            connector: 'and' as const,
            query: [
              {
                connector: 'and' as const,
                operator: 'startwith' as const,
                field: autoCompleteFiled,
                value: props.value,
              },
            ],
          },
        ],
      }).then((data: any) => {
        let disposeData: any = [];
        const [modelName, fieldName] = autoCompleteFiled.split('$');
        if (data.Rows && data.Rows?.length > 0) {
          data.Rows.forEach((item: any) => {
            disposeData.push({ value: item[fieldName], key: item['id'] });
          });
        }
        setOptions(disposeData);
      });
    }
  }, [props.value]);

  useEffect(() => {
    if (!loading && (!props.value || props.value?.length < 0)) {
      setOptions([]);
    }
  }, [props.value, loading]);

  useImperativeHandle(
    ref,
    () => ({
      ...api(configEvents, props, filed, options, setOptions),
    }),
    [options],
  );
  // 自动完成的专有方法
  const onSelect = (value: string, options: any) => {
    props.emit?.('onSelect', value, options);
  };
  const onSearch = (searchText: string) => {
    props.emit?.('onSerch', searchText);
  };

  return autoComplete ? (<>
    {viewMode == 'look' ? `${props.value}${props.addonAfter?props.addonAfter:''}`: <AutoComplete
      {...others}
      style={{ lineHeight: '31px' }}
      className="eformInput"
      disabled={props.readOnly || props.disabled}
      backfill
      options={options}
      onSelect={onSelect}
      onSearch={onSearch}
    >
      <Input
        addonAfter={props.addonAfter}
        size="middle"
        allowClear={allowClear}
        placeholder={placeholder}
        style={{ margin: 0 }}
        onChange={(e) => {
          props?.onChange?.(e.target.value.replace(iconNoEnterReg, ''));
        }}
      // allowClear={allowClear}
      />
    </AutoComplete>
    }
  </>
  ) : (
    <>
      {viewMode == 'look' ? `${props.value}${props.addonAfter?props.addonAfter:''}` :
        <Input
          {...others}
          className="eformInput"
          type={type}
          disabled={props.disabled || props.readOnly}
          allowClear={allowClear}
          placeholder={placeholder}
          onChange={(e) => {
            props?.onChange?.((e.target.value || '').replace(iconNoEnterReg, ''));
          }}
        />}
    </>
  );
});
EformInput.displayName = 'EformInput';

(
  EformInput as typeof EformInput & IDefaultValueFormat<typeof defaultProps>
).defaultValueFormat = (props: any): string | void => {
  if (props.defaultValueType == 'custom') {
    return props.customValue;
  } else if (props.defaultValueType == 'system' && props.systemDefaultValue) {
    const { userInfoByToken } = props.inbiz.appInfo;
    const data = {
      System_Var_LoginUserID: userInfoByToken.ID,
      System_Var_LoginUserIdentityId: userInfoByToken.IdentityId,
      System_Var_LoginUserName: userInfoByToken.Name,
      System_Var_LoginUserDeptID: userInfoByToken.MainDepartmentId,
      System_Var_LoginUserDeptName: userInfoByToken.MainDepartmentName,
      System_Var_LoginUserPostID: userInfoByToken.MainPositionId,
      System_Var_LoginUserPostName: userInfoByToken.MainPositionName,
      System_Var_LoginUserAccount: userInfoByToken.Account,
    };
    let result = '';
    for (const key in data) {
      if (key == props.systemDefaultValue) {
        result = data[key];
      }
    }
    return result;
  }
};

export default connect(
  EformInput,
  mapProps((props: IProps) => {
    const other = props;
    other.placeholder = getMessage(props.placeholder);
    return { ...other };
  }),
);
// export default EformInput;
export type { IProps };
